package com.oig.sys.workflow.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.oig.sys.workflow.app.IAppFlowInstanceService;
import com.oig.sys.workflow.constants.FlowEnums;
import com.oig.sys.workflow.flow.event.ApprovalStatusChangeEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class SpringEventListener {

    private final IAppFlowInstanceService appFlowInstanceService;

    @Async
    @EventListener(ApprovalStatusChangeEvent.class)
    public void flowStatusChange(ApprovalStatusChangeEvent event){
        log.debug("收到审批状态变更");
        String eventSource = (String) event.getSource();
        JSONObject jsonObject = JSON.parseObject(eventSource);
        JSONObject eventObject = jsonObject.getJSONObject("event");
        String instanceId = eventObject.getString("instance_code");
        String flowCode = eventObject.getString("approval_code");
        String status = eventObject.getString("status");
        if (FlowEnums.InstanceStatus.PENDING.getCode().equals(status)){
            log.debug("忽略pending状态");
            return;
        }
        appFlowInstanceService.updateFlowInstanceStatus(flowCode, instanceId, status);
    }

}
